"""
给你一个整数数组 nums ，判断是否存在三元组 [nums[i], nums[j], nums[k]]
满足 i != j、i != k 且 j != k ，同时还满足 nums[i] + nums[j] + nums[k] == 0 。
请你返回所有和为 0 且不重复的三元组。
注意：答案中不可以包含重复的三元组。
"""

from typing import List

from openpyxl.styles.builtins import total


# class Solution:
#     def threeSum(self, nums: List[int]) -> List[List[int]]:
#         nums.sort()  # 排序以便双指针和去重
#         res = []
#
#         for i in range(len(nums) - 2):
#             if i > 0 and nums[i] == nums[i - 1]:  # 跳过重复的第一个数
#                 continue
#
#             left, right = i + 1, len(nums) - 1
#             while left < right:
#                 total = nums[i] + nums[left] + nums[right]
#
#                 if total == 0:
#                     res.append([nums[i], nums[left], nums[right]])
#
#                     # 跳过重复的第二个数
#                     while left < right and nums[left] == nums[left + 1]:
#                         left += 1
#                     # 跳过重复的第三个数
#                     while left < right and nums[right] == nums[right - 1]:
#                         right -= 1
#
#                     left += 1
#                     right -= 1
#
#                 elif total < 0:
#                     left += 1
#                 else:
#                     right -= 1
#
#         return res
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        nums.sort()
        res = []


        for i in range(n):
            if nums[i] > 0:
                break
            if i > 0 and nums[i]==nums[i-1]:
                continue
            left,right = i+1,n-1
            while left < right:
                total = nums[i] + nums[left] + nums[right]
                if total == 0:
                    res.append([nums[i], nums[left], nums[right]])

                while left < right and nums[left] == nums[left+1]:
                    left += 1
                while right > left and nums[right] == nums[right-1]:
                    right -= 1
                left += 1
                right -= 1

                if total > 0:
                    right -= 1
                if total < 0:
                    left += 1
        return res
print(Solution().threeSum([-1,0,1,2,-1,-4]))
